
import Koa from 'koa'
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const R = require('ramda')
const {resolve} = require('path')

const host = process.env.HOST || '127.0.0.1'
const port = process.env.PORT || 3000

// Import and Set Nuxt.js options
let config = require('../nuxt.config.js')
config.dev = !(process.env === 'production')
const r = path => resolve(__dirname,path)
const MIDDLEWARES = ['database','router']

class Server{
  // 构造Server
  constructor() {
    this.app = new Koa();
    this.useMiddleWares(this.app)(MIDDLEWARES);
  }

  // 加载中间件
   useMiddleWares(napp){
    // this.app.use(mid1) // 加载中间件1
    // this.app.use(mid2) // 加载中间件2
    return R.map(R.pipe(i=>`${r('./middlewares')}/${i}`,require,R.map(i=>i(napp)))) //  加载数组中的中间件
   }
   // 启动服务
   async Start(){
   // Instantiate nuxt.js
   const nuxt = new Nuxt(config)

   // Build in development
     if (config.dev) {
     const builder = new Builder(nuxt)
     await builder.build()
    }

    this.app.use(ctx => {
      ctx.status = 200 // koa defaults to 404 when it sees that status is unset

      return new Promise((resolve, reject) => {
        ctx.res.on('close', resolve)
        ctx.res.on('finish', resolve)
        nuxt.render(ctx.req, ctx.res, promise => {
          // nuxt.render passes a rejected promise into callback on error.
          promise.then(resolve).catch(reject)
        })
      })
    })

    this.app.listen(port, host)
     consola.ready({
       message: `Server listening on http://${host}:${port}`,
        badge: true
     })
 }


}
  
const S1 = new Server();
S1.Start();